package com.example.rdb.conf.mysql;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @Version 1.0
 * @Author:徐衍程
 * @Date:2021/8/19
 * @Content:
 */
@Configuration
//@MapperScan(basePackages = "com.example.rdb.handle.mysql.write", sqlSessionFactoryRef = "mpWriteSqlSessionFactory")
public class MysqlConfigWriteMp {

//    @Primary // 表示这个数据源是默认数据源, 这个注解必须要加，因为不加的话spring将分不清楚那个为主数据源（默认数据源）
    @Bean("mpWriteDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.write-mp") //读取application.yml中的配置参数映射成为一个对象
    public DataSource mpWriteDataSource(){
        return DataSourceBuilder.create().build();
    }

//    @Primary
    @Bean("mpWriteSqlSessionFactory")
    public SqlSessionFactory mpWriteSqlSessionFactory(@Qualifier("mpWriteDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/write/*.xml"));
        return bean.getObject();
    }

//    @Primary
    @Bean("mpWriteSqlSessionTemplate")
    public SqlSessionTemplate mpWriteSqlSessionTemplate(@Qualifier("mpWriteSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
